/*
 * Copyright (c) 2009, Hamish Morgan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University of Sussex nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package locusts.server.collisions;

import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Hold a list of collidable objects and calculate if any of them intersect.
 *
 * Note:  known problem with this system is that thatdesting for object
 * intersection will fail when one object is wholy inside another. However
 * this has been done on purpose because it makes it much faster.
 *
 * @author Hamish Morgan Morgan
 */
public class CollisionSystem {

    private static final Logger LOG = LoggerFactory.getLogger(
            CollisionSystem.class);
    //
    private final List<Collidable> collidables;
    private ResponceStack[][] responces;

    private static final class ResponceStack
            extends CopyOnWriteArrayList<CollisionResponce> {
    }

    public CollisionSystem(List<Collidable> entities) {
        this.collidables = entities;
        responces = new ResponceStack[0][0];
    }

    public CollisionSystem() {
        this(new CopyOnWriteArrayList<Collidable>());
    }

    private void growResponceTable(int maxId) {
        if (responces.length <= maxId) {
            final ResponceStack[][] temp =
                    new ResponceStack[maxId + 1][maxId + 1];
            for (int i = 0; i < responces.length; i++)
                System.arraycopy(responces[i], 0, temp[i], 0, responces.length);
            for (int i = responces.length; i < temp.length; i++)
                for (int j = 0; j < temp.length; j++)
                    temp[i][j] = new ResponceStack();
            for (int i = 0; i < temp.length; i++)
                for (int j = responces.length; j < temp.length; j++)
                    temp[i][j] = new ResponceStack();
            responces = temp;
        }
    }

    public void addResponce(int aTypeId, int bTypeId,
            CollisionResponce responce) {
        growResponceTable(Math.max(aTypeId, bTypeId));
        responces[aTypeId][bTypeId].add(responce);
    }

    public void addResponce(Collidable a, Collidable b,
            CollisionResponce responce) {
        addResponce(a.getTypeId(), b.getTypeId(), responce);
    }

    public boolean isResponceSet(int aTypeId, int bTypeId) {
        return responces.length > bTypeId && responces.length > aTypeId &&
                responces[aTypeId][bTypeId].size() > 0;
    }

    public boolean isResponceSet(Collidable a, Collidable b) {
        return isResponceSet(a.getTypeId(), b.getTypeId());
    }

    public List<CollisionResponce> getResponces(int aTypeId, int bTypeId) {
        if (isResponceSet(aTypeId, bTypeId))
            return responces[aTypeId][bTypeId];
        else return Collections.emptyList();
    }

    public List<CollisionResponce> getResponces(Collidable a, Collidable b) {
        return getResponces(a.getTypeId(), b.getTypeId());
    }

    public void addCollidable(Collidable c) {
        synchronized (collidables) {
            collidables.add(c);
        }
    }

    public void removeCollidable(Collidable c) {
        synchronized (collidables) {
            collidables.remove(c);
        }
    }

    public Collidable getCollidable(int id) {
        synchronized (collidables) {
            for (Collidable c : collidables)
                if (c.getId() == id)
                    return c;
            return null;
        }
    }

    public final void doCollisions(Collidable a, double period) {
        List<Collidable> c = getCollisions(a, collidables);
        for (Collidable e : c)
            fireResponces(a, e, period);
    }

    public final void doCollisions(double period) {
        synchronized (collidables) {
            if (collidables.size() <= 1)
                return;
        }
        final List<Collidable[]> collisions = getCollisions();
        for (Collidable[] pair : collisions) {
            fireResponces(pair[0], pair[1], period);
        }
    }

    private final void fireResponces(Collidable a, Collidable b,
            double period) {
        for (CollisionResponce cr : getResponces(a, b))
            cr.doCollision(a, b, period);
        for (CollisionResponce cr : getResponces(b, a))
            cr.doCollision(b, a, period);
    }

    private final List<Collidable[]> getCollisions() {
        final List<Collidable[]> result = new ArrayList<Collidable[]>();
        synchronized (collidables) {
            if (collidables.size() <= 1)
                return result;
        }

        int count = 0;
        synchronized (collidables) {
            for (int i = 0; i < collidables.size(); i++) {
                final Collidable a = collidables.get(i);

                final List<Collidable> c = getCollisions(a, collidables.
                        subList(
                        i + 1, collidables.size()));

                for (Collidable b : c) {
                    result.add(new Collidable[]{a, b});
                    count++;
                }
            }
        }

        LOG.debug("Found {} collisions", count);
        return result;
    }

    private final List<Collidable> getCollisions(Collidable a,
            List<Collidable> collidables) {
        final List<Collidable> result = new ArrayList<Collidable>();

        synchronized (collidables) {
            for (Collidable b : collidables) {
                if (a.getId() == b.getId())
                    continue;

                if (!isResponceSet(a, b) && !isResponceSet(b, a))
                    continue;

                if (!isClose(a, b))
                    continue;

                if (intersects(a, b)) {
                    result.add(b);
                }
            }
        }
        return result;
    }

    private final boolean intersects(Collidable a, Collidable b) {

        Shape aShape = a.getShape();
        Shape bShape = b.getShape();

        if (aShape instanceof Ellipse2D) {
            if (bShape instanceof Ellipse2D) {
                return true;
            }
        }
        return slowIntersects(a, b);
    }

    /**
     * Calculate quickly if the two objects are likely to be close
     * to collision.
     *
     * @param a
     * @param b
     * @return
     */
    private final boolean isClose(final Collidable a,
            final Collidable b) {
        final double minDist = a.getMaxRadius() + b.getMaxRadius();
        final double dx = b.getX() - a.getX();
        final double dy = b.getY() - a.getY();
        return dx * dx + dy * dy <= minDist * minDist;
    }

    protected static final Area getIntersection(
            Collidable a, Collidable b) {
        Area aArea = a.geTransformedArea();
        Area bArea = b.geTransformedArea();
        aArea.intersect(bArea);
        return aArea;

    }

    /**
     * Very accurate but slow intersection check. Seems to throw random errors
     * some times.
     *
     * @param a
     * @param b
     * @return
     */
    private final boolean slowIntersects(Collidable a, Collidable b) {
        Area i = getIntersection(a, b);
        return !i.isEmpty();
    }
}
